//
//  NSObject+UIViewController.m
//  zoomlion-door
//
//  Created by 余鑫 on 2020/5/6.
//  Copyright © 2020 Zoomlion. All rights reserved.
//

#import "NSObject+UIViewController.h"
#define Index 10 //最大递归层数 不建议一直迭代模态弹出视图

@implementation NSObject (UIViewController)

- (UIViewController *)zlzk_viewController {
    UIViewController *vc = [UIApplication sharedApplication].keyWindow.rootViewController;
    
    //modal
    if (vc.presentedViewController) {
        //UINavigationController导航控制器
        if ([vc.presentedViewController isKindOfClass:[UINavigationController class]]) {
            
            UINavigationController *navVc = (UINavigationController *)vc.presentedViewController;
            vc = navVc.visibleViewController;
        
        //UITabBarController导航控制器
        } else if ([vc.presentedViewController isKindOfClass:[UITabBarController class]]) {
            
            UITabBarController *tabVc = (UITabBarController *)vc.presentedViewController;
            //tabbar为导航控制器
            if ([tabVc.selectedViewController isKindOfClass:[UINavigationBar class]]) {
                
                UINavigationController *navVc = (UINavigationController *)tabVc.selectedViewController;
                return navVc.visibleViewController;
            //tabbar为常规控制器
            } else {
                
                return tabVc.selectedViewController;
            }
        } else {
            
            //多层present拓展
            // 当多层present时,循环递归返回栈顶的控制器,
            UIViewController *viewController = vc;
            int index = Index;
            while (true) {
                UIViewController *temp = viewController.presentedViewController;
                if (temp == nil || index < 0) {
                    // 此处想回到哪层 判断一下控制器类 返回即可
                    return viewController;
                }
                viewController = temp;
                index --;
            }
        }
    } else {//push
    
        // 根视图为tab导航控制器
        if ([vc isKindOfClass:[UITabBarController class]]) {
            
            UITabBarController *tabVc = (UITabBarController *)vc;
            //当前显示的tabbar为UINavigationController导航控制器
            if ([tabVc.selectedViewController isKindOfClass: [UINavigationController class]]) {
                
                UINavigationController *navVc = (UINavigationController *)tabVc.selectedViewController;
                return navVc.visibleViewController;
            } else {
                
                return tabVc.selectedViewController;
            }
        // 根视图为UINavigationController导航控制器
        } else if ([vc isKindOfClass:[UINavigationController class]]) {
            
            UINavigationController *navVc = (UINavigationController *)vc;
            vc = navVc.visibleViewController;
        }
    }
    
    return vc;
}

@end
